package com.document.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SecurityUtils {

    /**
     * 获取当前登录用户ID
     */
    public static Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.debug("Authentication object: {}", authentication);

        if (authentication != null && authentication.isAuthenticated() && authentication.getPrincipal() != null) {
            Object principal = authentication.getPrincipal();
            log.debug("Principal type: {}, value: {}", principal.getClass().getName(), principal);

            try {
                // 检查是否是匿名用户
                if ("anonymousUser".equals(principal)) {
                    throw new RuntimeException("用户未登录");
                }

                // 如果 principal 是 Long 类型（用户ID）
                if (principal instanceof Long) {
                    return (Long) principal;
                }

                // 如果 principal 是 String 类型，尝试转换为 Long
                if (principal instanceof String) {
                    String principalStr = (String) principal;
                    // 检查是否是数字字符串
                    if (principalStr.matches("\\d+")) {
                        return Long.valueOf(principalStr);
                    } else {
                        throw new RuntimeException("用户ID格式错误: " + principalStr);
                    }
                }

                throw new RuntimeException("不支持的 Principal 类型: " + principal.getClass().getName());
            } catch (NumberFormatException e) {
                log.error("用户ID格式转换错误: {}", e.getMessage());
                throw new RuntimeException("用户ID格式错误");
            }
        }
        throw new RuntimeException("用户未登录");
    }

    /**
     * 检查用户是否已登录
     */
    public static boolean isLoggedIn() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated()
                && !"anonymousUser".equals(authentication.getPrincipal());
    }
}